package com.glodon.paas.account.security.oauth2.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * @author Don Li
 */
@Controller
public class TokenManagementService {
    @Autowired
    private TokenStore tokenStore;

    @RequestMapping(value = "/oauth2/invalid_token")
    @ResponseStatus(HttpStatus.OK)
    public void invalidateTokens() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            for (OAuth2AccessToken accessToken : tokenStore.findTokensByUserName(authentication.getName())) {
                OAuth2RefreshToken refreshToken = accessToken.getRefreshToken();
                tokenStore.removeAccessToken(accessToken);
                tokenStore.removeRefreshToken(refreshToken);
            }
        }
    }
    
    
}
